package org.mapformat.parser;

import java.text.FieldPosition;
import java.text.MessageFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.mapformat.MapFormat;


@SuppressWarnings("serial")
public class MessageMapFormat extends MapFormat {

	public MessageMapFormat(String pattern) {
		applyPattern(pattern);
	}

	private String pattern = null;
	private List<String> keys = new ArrayList<String>();

	public void applyPattern(String pattern) {
		this.pattern = pattern;
		if (this.pattern != null && !"".equals(this.pattern)) {
			StringBuffer sb = new StringBuffer();
			for(int i = 0, l = this.pattern.length(); i < l; i++) {
				switch(this.pattern.charAt(i)) {
				case '$':
					i++;
					if (this.pattern.charAt(i) == '{') {
						sb.append(this.pattern.charAt(i));
						i++;
						StringBuffer key = new StringBuffer();
						while(this.pattern.charAt(i) != '}' && this.pattern.charAt(i) != ',') {
							key.append(this.pattern.charAt(i));
							i++;
						}
						sb.append(""+keys.size()).append(this.pattern.charAt(i));
						if (!"".equals(key.toString())) {
							keys.add(key.toString());
						}
					}
					break;
				default:
					sb.append(this.pattern.charAt(i));
					break;
				}
			}
			this.pattern = sb.toString();
		}
		
	}

	@Override
	public StringBuffer format(Object obj, StringBuffer toAppendTo,
			FieldPosition pos) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public Object parseObject(String source, ParsePosition pos) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	public String format(Map map){
        List<Object> arguments = new ArrayList();
        for( String key: this.keys ){
            Object value = map.get(key);
            arguments.add(value);
        }
        MessageFormat mf = new MessageFormat(this.pattern);
        return mf.format(arguments.toArray());
    }

	public String getPattern() {
        return pattern;
    }
	
	public List<String> getKeys() {
        return keys;
    }
	
}
